<template>
    <div>
      <el-upload
        class="upload-oss"
        drag
        :action="uploadUrl"
        :auto-upload="false"
        :accept="accept"
        ref="fileUpload"
        :show-file-list="false"
        :on-exceed="handleExceed"
        :on-change="fnUploadChange"
        :http-request="fnUploadRequest"
        :limit = "limit"
        :multiple="limit>1"
        :disabled="disabled"
        :file-list="fileList"
        :before-upload="beforeUpload"
        >
        <slot></slot>
      </el-upload>
    </div>
  </template>
  <script>
  import * as message from "@/constants/message";
  import * as Constants from "@/constants/constants";
  import ComponentApi from "@/api/components/component";
  export default {
    name: 'fileUpload',
    props: {
      folder: { // 上传至OSS的文件夹路径
        type: String,
        required: true
      },
      index:{ //传过来的索引
        type:Number,
        default:undefined
      },
      param:{ //传过来的参数
        type:Object,
        default:undefined
      },
      limit:{
        type: Number,
        default: 1
      },
      accept: {
        type: String,
        default:".png,.jpg,.jpeg,.bmp"
      }
    },
    data () {
      return {
        imgUrl:"",
        ossClient: null,
        uploadUrl: '#',
        fileList: [],
        uploadHeaders: {
          authorization: ''
        },
        uploadFileList: [],
        chooseFileLength: 0,
        submitLoading: false,
        disabled: false
      }
    },
    watch: {

    },
    methods: {
      async fnUploadRequest (option) {
        try {
          const _this = this
          // 判断已经上传过的不处理--情景：先上传成功3个，后补充1个，之前3个会循环调用。
          if (option && option.response && option.response.url) {
            return
          }
          // 当前上传的文件
          let file = option.file
          const fileName = file.name
          const fileType = fileName.split("\.")[1];
          /*let fileTempName = _this.$Utils.mathRand() + fileName.split("\.")[0];
          if (fileTempName.length > 12){
            fileTempName = fileTempName.substring(0,12);
          }*/
          const newName = _this.$Utils.mathRand19() +"."+ fileType;
          const storeAs = Constants.OSS_WEB_URL + _this.folder + '/' + newName;
          //console.log('开始上传，文件名>>>>>' + fileName)
          // TODO 测试 注释上传动作
          _this.ossClient.put(storeAs, file, {}).then(
            function (ret) {
              if (ret.res.statusCode === 200) {
                let realUrl = ret.url.replace(Constants.OSS_URL,Constants.OSS_REAL_URL);
                ret.url = realUrl;
                _this.uploadFileList = [realUrl]
                // _this.uploadFileList.push(realUrl);
                //console.log('上传成功，文件名>>>>>' + fileName)
                //console.log('上传成功，_this.uploadFileList>>>>>' + _this.uploadFileList)
                //option.onSuccess(ret)
                // 值回传
                option.response = ret
                return ret
              } else {
                option.onError('上传失败')
              }
            }
          ).catch(function (err) {
            console.error(err)
          })
        } catch (error) {
          console.error(error)
          this.disabled = false
          option.onError('上传失败')
          this.$error(error.message)
        }
      },

      fnUploadChange (file, fileList) {
        if(fileList.length>1){
            fileList.splice(0,1)
        }
        this.chooseFileLength = fileList.length
        // this.$emit('chooseFileLength', this.chooseFileLength)
        // window.URL.createObjectURL(file.raw)
        this.sureUpload()


      },
      beforeUpload(val) {
          if (val.size / 1024 / 1024 > 5) {
              this.$message.error("大小不能超过5MB")
              return false
          } else {
              return
          }
      },
      handleExceed(list){
        this.$message.error("最多可以选择"+this.limit+'张图片')
      },
      /**
       * el-upload
       * on-before	文件上传前限制时的钩子
       *  */
      // fnBeforeUpload (file) {
      //   let _this = this
      //   if (_this.accept != 'all'){
      //     const result = _this.$Utils.matchType(file.name);
      //     if (_this.accept.indexOf(result) == -1) {
      //       _this.$message.error('文件格式不支持!');
      //       return false;
      //     }
      //     let size = 20
      //     if (_this.accept == 'video' || _this.accept == 'excel'){
      //       size = 50
      //     }
      //     const isLt2M = file.size / 1024 / 1024 < size;
      //     if (!isLt2M) {
      //       _this.$message.error(`文件大小不能超过 ${size}MB!`)
      //       return false;
      //     }
      //   }
      //   return true;
      // },
      sureUpload() {

        // return
        let _this = this
        // 判断是否有选择文件
        // if (_this.chooseFileLength == 0){
        //   _this.$message.error('您未选择需上传的文件!')
        //   return
        // }
        _this.submitLoading = true
        // 请求oss，获取授权
        ComponentApi.uploadOss().then(res => {
          let OSS = require('ali-oss')
          _this.ossClient = new OSS({
            region: Constants.OSS_REGION,
            accessKeyId: res.data.accessKeyId,
            accessKeySecret: res.data.accessKeySecret,
            stsToken: res.data.securityToken,
            bucket: Constants.OSS_BUCKET
          })
          _this.$refs.fileUpload.submit()
          _this.$refs.fileUpload.clearFiles()
          const timer = setTimeout(() => {
            // 根据上传个数相等，判断是否已上传完毕
            if (_this.uploadFileList.length>0 && _this.uploadFileList.length === _this.chooseFileLength){
              // 使用$emit出发父组件的自定义事件
              if(_this.index || _this.index===0 || _this.param){
                let rtnObj = {uploadFileList:this.uploadFileList}
                if (_this.index || _this.index===0){
                  rtnObj.index = this.index
                }
                if (_this.param){
                  rtnObj.param = this.param
                }
                _this.$emit('uploadFileList',rtnObj )
              }else{
                _this.$emit('uploadFileList', this.uploadFileList)
              }

              //console.log(666,JSON.stringify(this.uploadFileList))
              _this.submitLoading = false
              clearTimeout(timer);
            }
          }, 500)
        }).catch(error => {
          _this.submitLoading = false
          _this.$notify.error({
            title: message.TITLE_ERROR,
            message: "上传失败，请稍后再试！"
          })
        })

      },
      handleCreate() {
        // 清空旧文件 - 上一次弹窗上传过的文件
        this.fileList = []
        this.uploadFileList = []
      }
    }
  }
  </script>

  <style lang="scss">
    .el-upload-dragger{
          width: 300px;
        }
</style>
